﻿Imports Cls_Common
Imports System.IO
Imports VSModel

Partial Class Control_Customer_UploadFile
    Inherits System.Web.UI.UserControl

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        If FileUpload1.HasFile AndAlso (FileUpload1.FileName.Contains("dbf") Or FileUpload1.FileName.Contains("DBF")) Then

            Dim rootPath As String = Context.Server.MapPath("~/Uploads/")

            Dim intFileNameLength As Integer
            Dim strFileName As String
            Dim random As New Random
            'Logic to find the FileName (excluding the path)
            Dim DestPath = rootPath & "\" & Now.Year.ToString.Trim() & "\" & Now.Month.ToString.Trim() & "-" & Now.Day.ToString.Trim()
            Dim StringDate = Now.Year.ToString.Trim() & "/" & Now.Month.ToString.Trim() & "-" & Now.Day.ToString.Trim()
            'create thu mutc theo year + month
            If Not Directory.Exists(DestPath) Then
                Directory.CreateDirectory(DestPath)
            End If
            strFileName = FileUpload1.FileName
            'neu ton tai file name 
            If (System.IO.File.Exists(DestPath & "/" & strFileName)) Then
                intFileNameLength = InStr(1, StrReverse(strFileName), "\")
                strFileName = (random.NextDouble + 65).ToString + strFileName
                FileUpload1.SaveAs(DestPath & "/" & strFileName)
            Else
                FileUpload1.SaveAs(DestPath & "/" & strFileName)
            End If
            'update vao file
            Using _data As New VSEntities
                Dim p As New VSModel.TBFile
                p.FileName = strFileName
                p.FileURL = DestPath & "/" & strFileName 'MainDomain & "uploads/" & DestPath.Replace(rootPath, "").Replace("\", "/") & strFileName
                p.Created = Now
                p.Creator = Session("UserName")
                _data.TBFiles.AddObject(p)
                _data.SaveChanges()
            End Using


            Excute_Javascript("Alertbox('Upload file dữ liệu thành công.');", Me.Page, True)
            Response.Redirect("upload-file.html")


        Else
            Excute_Javascript("Alertbox('Định dạng file không phù hợp.');", Me.Page, True)

        End If

    End Sub
    Private Sub BindToGrid(Optional ByVal iPage As Integer = 1, Optional ByVal strSearch As String = "")
        Using data As New VSEntities
            'So ban ghi muon the hien tren trang
            Dim intPag_Size As Int32 = drpPage_Size.SelectedValue
            Dim _Creator As String = Session("UserName")
            Dim p = (From q In data.TBFiles Where q.FileName.Contains(strSearch) And q.Creator = _Creator Order By q.Id Descending Select q).Skip((iPage - 1) * intPag_Size).Take(intPag_Size).ToList
            Dim strKey_Name() As String = {"Id", "FileName"}
            'Tong so ban ghi
            hidCount.Value = p.Count
            Create_Pager(hidCount.Value, iPage, intPag_Size, 10)
            With grdShow
                .DataKeyNames = strKey_Name
                .DataSource = p
                .DataBind()
            End With
            lblTotal.Text = "Hiển thị " + (((iPage - 1) * intPag_Size) + 1).ToString + " đến " + (((iPage - 1) * intPag_Size) + grdShow.Rows.Count).ToString + " trong tổng số " + hidCount.Value.ToString + " bản ghi."
        End Using
    End Sub
    Sub Create_Pager(ByVal Total_Record As Integer, ByVal Page_Index As Integer, ByVal Page_Size As Integer, ByVal Page2Show As Integer)
        Dim TotalPage As Integer = IIf((Total_Record Mod Page_Size) = 0, Total_Record / Page_Size, Total_Record \ Page_Size + 1)
        'lu lai tong so ban ghi
        hidIndex_page.Value = TotalPage
        'gan lai curPage de set active
        hidCur_Page.Value = Page_Index
        'generate ra left page
        Dim cPageGenerate_left As IEnumerable(Of Integer)
        If Page_Index <= Page2Show Then
            cPageGenerate_left = Enumerable.Range(1, Page_Index)
        Else
            cPageGenerate_left = Enumerable.Range(Page_Index - Page2Show, Page2Show)
        End If
        'generate ra right page
        Dim cPageGenerate_Right As IEnumerable(Of Integer)
        If Page_Index + Page2Show <= TotalPage Then
            cPageGenerate_Right = Enumerable.Range(Page_Index, Page2Show + 1)
        Else
            cPageGenerate_Right = Enumerable.Range(Page_Index, TotalPage - Page_Index + 1)
        End If
        'union 2 range va bind to Grid
        With rptPage
            .DataSource = cPageGenerate_left.Union(cPageGenerate_Right)
            .DataBind()
        End With
    End Sub
    Protected Sub rptPage_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptPage.ItemDataBound
        Dim lnkTitle As LinkButton
        lnkTitle = e.Item.FindControl("lnkTitle")
        Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
        ScriptManager.RegisterAsyncPostBackControl(lnkTitle)
        If e.Item.DataItem = hidCur_Page.Value Then
            lnkTitle.Text = "<span class='current'>" & e.Item.DataItem & "</span>"
        Else
            lnkTitle.Text = "<span>" & e.Item.DataItem & "</span>"
        End If
        lnkTitle.ToolTip = e.Item.DataItem
    End Sub
    Protected Sub lnkTitle_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lnkTile As LinkButton = CType(sender, LinkButton)
        BindToGrid(lnkTile.ToolTip)
        lnkLast.Enabled = True
        lnkFirst.Enabled = True
        If CInt(lnkTile.ToolTip) = hidIndex_page.Value Then
            lnkLast.Enabled = False
        ElseIf CInt(lnkTile.ToolTip) = 1 Then
            lnkFirst.Enabled = False
        End If
    End Sub
    Protected Sub lnkFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkFirst.Click
        If hidCur_Page.Value > 1 Then
            hidCur_Page.Value = hidCur_Page.Value - 1
        End If
        BindToGrid(hidCur_Page.Value)
    End Sub
    Protected Sub lnkLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLast.Click
        hidCur_Page.Value = hidCur_Page.Value + 1
        BindToGrid(hidCur_Page.Value)
    End Sub


    Protected Sub lnkbtnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim intId As Integer
        Dim strLogName As String = ""
        Using data As New VSEntities
            intId = grdShow.DataKeys(hidID.Value)("Id").ToString
            Dim q = (From p In data.TBFiles Where p.Id = intId Select p).FirstOrDefault
            Try
                data.TBFiles.DeleteObject(q)
                data.SaveChanges()
                'delete system
                If (System.IO.File.Exists(q.FileURL)) Then
                    File.Delete(q.FileURL)
                End If

       

                'Insert_App_Log("Insert  Files:" & txtTitle.Text.Trim & "", Function_Name.Files, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                Excute_Javascript("Alertbox('Xóa dữ liệu thành công.');", Me.Page, True)
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()

                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End Try
        End Using
        BindToGrid()
    End Sub
    
    Protected Sub grdShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShow.RowDataBound
        If e.Row.RowIndex >= 0 Then

            Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
            lblSTT.Text = CInt(drpPage_Size.SelectedValue) * (CInt(hidCur_Page.Value) - 1).ToString + e.Row.RowIndex + 1
            Dim lnkbtnDelete As LinkButton = CType(e.Row.FindControl("lnkbtnDelete"), LinkButton)
            lnkbtnDelete.Attributes.Add("onclick", "return ComfirmDialog('" + drpMessage.Items(0).Text + "', 0,'" + lnkbtnDelete.ClientID + "','" + e.Row.RowIndex.ToString + "',1);")
            Dim hplEdit As HyperLink = CType(e.Row.FindControl("hplEdit"), HyperLink)
            Dim hplFilename As HyperLink = CType(e.Row.FindControl("hplFilename"), HyperLink)
            hplFilename.Text = grdShow.DataKeys(e.Row.RowIndex)("FileName").ToString
            hplFilename.NavigateUrl = ""
        End If
    End Sub
    Protected Sub btnFilter_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFilter.Click
        BindToGrid(1, txtTitleFilter.Text.Trim())
    End Sub



    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            BindToGrid()

        End If
    End Sub
End Class
